#include "Ordinary.h"
#include <iostream>
#include <thread>
#include <iomanip>
#include <ctime>

static communicate_data indata = {"", ""};
static string model_response = "";
static string end_flag = "false";
static string default_history_path = "../conversations/刚刚.json";

std::string getCurrentTimeFormatted() {
    // 获取当前时间
    std::time_t now = std::time(nullptr);
    std::tm* ltm = std::localtime(&now);

    // 创建一个字符串流用于格式化时间
    std::ostringstream oss;

    // 格式化为“月份-日期-时钟-分钟”
    oss << std::setw(2) << std::setfill('0') << ltm->tm_mon + 1 << "月" // 月份（tm_mon 从 0 开始，所以加 1）
        << std::setw(2) << std::setfill('0') << ltm->tm_mday << "日"   // 日期
        << std::setw(2) << std::setfill('0') << ltm->tm_hour << "时"   // 时钟
        << std::setw(2) << std::setfill('0') << ltm->tm_min  << "分";          // 分钟

    return oss.str();
}

Ordinary::Ordinary()
{
    static GMainLoop *loop = g_main_loop_new(nullptr, FALSE);
    std::thread eventThread([]()
                            {
        g_main_loop_run(loop);
        g_main_loop_unref(loop); });
    eventThread.detach();

    config = chat_model_config_create();

    chat_model_config_set_name(config, "Qwen-2.5-3b_1.0");
    chat_model_config_set_top_k(config, 0.5);
    chat_model_config_set_deploy_type(config, ModelDeployType::OnDevice);

    session = genai_text_create_session();

    genai_text_set_model_config(session, config);
    genai_text_init_session(session);
    genai_text_set_chat_system_prompt(session, "你是一个聪明的AI助手，名字叫做小麒麟。");

    genai_text_result_set_callback(session, Ordinary::chat_callback, this); // ← this 传入 callback

    historyManager = new HistoryManager();
    historyManager->createHistoryFile(default_history_path);
}

Ordinary::~Ordinary()
{
    if (historyManager->deleteEmptyJsonFile(default_history_path) == 3){ // 有内容才保存
        historyManager->resetName(default_history_path, getCurrentTimeFormatted() + ".json");
    }
    
    
    if (config)
        chat_model_config_destroy(&config);

    if (session)
    {
        genai_text_stop_chat(session);
        genai_text_destroy_session(&session);
    }

    if (historyManager)
        delete historyManager;
}

string Ordinary::chat_with_model(string input_text)
{
    indata.user_query = input_text;
    model_response = "";
    end_flag = "false";

    {
        std::lock_guard<std::mutex> lock(sync_mutex);
        reply_ready = false;
    }

    genai_text_chat_async(session, input_text.c_str());

    // 等待回调通知
    std::unique_lock<std::mutex> lock(sync_mutex);
    cv.wait(lock, [this]()
            { return reply_ready; });

    return model_response;
}

// 封装的静态成员回调函数
void Ordinary::chat_callback(ChatResult *result, void *user_data)
{
    Ordinary *self = static_cast<Ordinary *>(user_data);

    const char *message = chat_result_get_assistant_message(result);
    end_flag = chat_result_get_is_end(result) ? "true" : "false";

    if (end_flag == "false")
    {
        indata.model_reply += message;
    }
    else
    {
        indata.model_reply += message;
        model_response = indata.model_reply;

        if (indata.model_reply != "<|stopChat_8167431|>")
        {
            HistoryManager interimHM;
            interimHM.saveTurn(indata.user_query, indata.model_reply, default_history_path);
        }

        indata.user_query = "";
        indata.model_reply = "";

        {
            std::lock_guard<std::mutex> lock(self->sync_mutex);
            self->reply_ready = true;
        }
        self->cv.notify_one();
    }
}
